//
//  DestinationTableViewController.m
//  TeamProject_Travel
//
//  Created by lanou3g on 16/3/25.
//  Copyright © 2016年 lanou3g. All rights reserved.
//
#import "DestinationDetailTableViewController.h"
#import "DestinationTableViewController.h"
#import "DestinationTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "DestinationModel.h"
#import "CDHttpHelper.h"
#import "SDRefresh.h"
#import "DesModel.h"
@interface DestinationTableViewController ()

@property(nonatomic,strong)SDRefreshFooterView * refreshFooter;
@property (nonatomic, weak) SDRefreshHeaderView *refreshHeader;
@property (nonatomic, assign) NSInteger totalRowCount;
@property(nonatomic,strong)NSMutableArray * allDataArray;
@property(nonatomic,strong)NSMutableArray * allDesArray;
@property(nonatomic,strong)NSMutableArray * GroupArray;
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)CGFloat widthOfRow;

@end

@implementation DestinationTableViewController

- (void)viewDidLoad {
    
    /*
     
     攻略详情下级的景点界面
     
     */
    
    
    [super viewDidLoad];
    
//    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.title = [self.strategyModel.name_zh_cn stringByAppendingString:@"景点"];
    
    self.allDataArray = [NSMutableArray array];
    self.allDesArray = [NSMutableArray array];
    self.GroupArray = [NSMutableArray array];
    self.dataArray = [NSMutableArray array];
    
    self.totalRowCount = 1;
    
    [self.tableView registerClass:[DestinationTableViewCell class] forCellReuseIdentifier:@"destination"];
    
    [self handleData];
    [self setupFooter];
    [self setupHeader];

}

- (void)setupHeader
{
    if (self.totalRowCount > 1) {
        self.totalRowCount -= 1;
    }else{
        self.totalRowCount = 1;
    }
    
    SDRefreshHeaderView *refreshHeader = [SDRefreshHeaderView refreshView];
    
    // 默认是在navigationController环境下，如果不是在此环境下，请设置
    refreshHeader.isEffectedByNavigationController = NO;
    [refreshHeader addToScrollView:self.tableView];
    
    __weak SDRefreshHeaderView *weakRefreshHeader = refreshHeader;
    __weak typeof(self) weakSelf = self;
    refreshHeader.beginRefreshingOperation = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.totalRowCount += 3;
            [weakSelf.tableView reloadData];
            [weakRefreshHeader endRefreshing];
        });
    };
    
    // 进入页面自动加载一次数据
    [refreshHeader autoRefreshWhenViewDidAppear];
}

-(void)setupFooter
{
    self.refreshFooter = [SDRefreshFooterView refreshView];
    [self.refreshFooter addToScrollView:self.tableView];
    [self.refreshFooter addTarget:self refreshAction:@selector(footerRefresh)];
    _refreshFooter = self.refreshFooter;
    
}
- (void)footerRefresh
{
    self.totalRowCount +=1;
    
    
    [self handleData];
    [self.refreshFooter endRefreshing];
}
//修改,,,,,全部加载后排序,分组显示给不同的点击cell
- (void)handleData1{

    for (int i = 0; i < 42; i++) {
        [[CDHttpHelper defaultCDHttpHelper] get:[NSString stringWithFormat:@"https://chanyouji.com/api/attractions.json?lat=%f&lng=%f&page=%d",self.strategyModel.lat,self.strategyModel.lng,i] params:nil success:^(id responseObj) {
            NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            [self.dataArray addObjectsFromArray:array];
//            NSLog(@"%ld",array.count);
            for (NSDictionary *dict in array) {
                [self.dataArray addObject:dict];
            }
            if (i == 41) {
                [self handleArrayData:self.dataArray];
//                NSLog(@"%ld",self.dataArray.count);
            }
        }failure:^(NSError *error) {
            
        }];

    }
    
}

- (void)handleArrayData:(NSMutableArray *)array{
    for (NSDictionary *dict in array) {
        [[CDHttpHelper defaultCDHttpHelper] get:[NSString stringWithFormat:@"https://chanyouji.com/api/attractions/%@.json?page=1",dict[@"id"]] params:nil success:^(id responseObj) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            DesModel *model = [DesModel new];
            [model setValuesForKeysWithDictionary:dic];
            [self.allDataArray addObject:model];
//            NSLog(@"%ld",array.count);
//            NSLog(@"+++++++%ld",self.allDataArray.count);
            if (self.allDataArray.count > self.totalRowCount * 10) {
                [self destinationGroupArray:self.allDataArray];
            }
        }failure:^(NSError *error) {
        }];
    }
}

- (void)destinationGroupArray:(NSMutableArray *)array{
    [self.GroupArray addObject:self.allDataArray];
    for (int i = 0; i < self.numArray.count; i++) {
        for (DesModel *model in self.allDataArray) {
            NSMutableArray *array1 = [NSMutableArray array];
            if ([model.name_zh_cn isEqualToString:self.numArray[i]]) {
                [array addObject:model];
            }
            [self.GroupArray addObject:array1];
        }
    }
    [self addFromArray:self.GroupArray];
}

- (void)addFromArray:(NSMutableArray *)array{
    for (NSInteger i = (self.totalRowCount - 1) * 10; i < self.totalRowCount * 10; i++) {
        [self.allDesArray addObject:self.GroupArray[i]];
    }
    [self.tableView reloadData];
}

- (void)handleData{
    
    [[CDHttpHelper defaultCDHttpHelper] get:[NSString stringWithFormat:@"https://chanyouji.com/api/attractions.json?lat=%f&lng=%f&page=%ld",self.strategyModel.lat,self.strategyModel.lng,self.totalRowCount] params:nil success:^(id responseObj) {
       
        NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        for (NSDictionary *dict in array) {
            [[CDHttpHelper defaultCDHttpHelper] get:[NSString stringWithFormat:@"https://chanyouji.com/api/attractions/%@.json?page=1",dict[@"id"]] params:nil success:^(id responseObj) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
                if (dic != nil) {
                    DesModel *model = [DesModel new];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.allDesArray addObject:model];
                   
                }

                 [self.tableView reloadData];
            } failure:^(NSError *error) {
                
            }];
        }
        
       
    } failure:^(NSError *error) {
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DesModel *desModel = self.allDesArray[indexPath.row];
    DestinationDetailTableViewController *detailVC = [[DestinationDetailTableViewController alloc]init];
    detailVC.ID = desModel.id;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.allDesArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DestinationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"destination" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[DestinationTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"destination"];
    }
    DesModel *model = self.allDesArray[indexPath.row];

    cell.countLabel.text = [NSString stringWithFormat:@"%ld 篇游记",model.attraction_trips_count];//需要后面页面传值
    cell.descriptionLabel.text = model.descriptions;//需要后面页面传值
    if (model.attraction_trips_count == 0) {
        cell.countLabel.text = @"";
        cell.countLabel.alpha = 0;
    }
   
    [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:model.image_url]];
    cell.titlelabel.text = model.name_zh_cn;
    
   //清空星值
    for (int i = 1; i <= 5; i++) {
        UIImageView *imageView = (UIImageView *)[self.view viewWithTag:i];
        imageView.image = [UIImage imageNamed:@"starK.png"];
    }
    //改变星值
    NSInteger count = [model.user_score floatValue];
    for (int i = 1; i <= count; i++) {
        UIImageView *imageView = (UIImageView *)[self.view viewWithTag:i];
        imageView.image = [UIImage imageNamed:@"starS.png"];
    }
    self.widthOfRow = cell.backImageView.frame.size.height + 10;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.widthOfRow;
}


@end
